package ssi.actions;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import ssi.beans.EditUserForm;
import ssi.tools.Type;
import ssi.tools.Connector;

public class ChangeTypeAction  extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		request.setCharacterEncoding("UTF-8");
		String target=null;
		
		EditUserForm changeForm = (EditUserForm) form;
		String email = changeForm.getEmail();
		String type = changeForm.getType();
		ActionErrors actionErrors = new ActionErrors();
		
		
		try{
			Connection connection = new Connector().getConnection();
    		Statement statement = connection.createStatement();
    		statement.setMaxRows(1);
    		ResultSet result = statement.executeQuery("SELECT type FROM `users` WHERE email=\""+ email + "\"");
    		if(result.next()){
    			statement.executeUpdate("Update users set type=\""+Type.valueOf(type)+"\" where email=\""+email+"\"");
    			target="success";
				result.close();
				connection.close();
				actionErrors.add("info",
						new ActionMessage("error.userTypeChanged"));
    		}else{
    			target="failure";
				result.close();
				connection.close();
				actionErrors.add("info",
						new ActionMessage("error.nouser"));
    		}
		}catch(Exception e){
			actionErrors.add("info",
					new ActionMessage("error.catch"));
		}
		if(actionErrors.size() !=0){
			extracted(request, actionErrors);
			return new ActionForward(mapping.getInput());
		}
		return mapping.findForward(target);
	}
	

	private void extracted(HttpServletRequest request, ActionErrors actionErrors) {
		saveErrors(request, actionErrors);
	}
}
